import {
  createReactBlockSpec,
  createReactInlineContentSpec,
  getDefaultReactSlashMenuItems,
  SuggestionMenuController,
  useCreateBlockNote,
  type DefaultReactSuggestionItem
} from "@blocknote/react";
import { BlockNoteView } from "@blocknote/shadcn";

// 语言包
import { zh } from "@blocknote/core/locales";
// shadcn 主题
import "@blocknote/shadcn/style.css";
import {
  BlockNoteSchema,
  defaultBlockSpecs,
  defaultInlineContentSpecs,
  defaultStyleSpecs,
  filterSuggestionItems,
  insertOrUpdateBlock
} from "@blocknote/core";

import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";
import { cursorRender } from "./cursorRender";

const ydoc = new Y.Doc();
// 使用 Yjs 实现协作编辑
const provider = new WebsocketProvider("ws://localhost:3000", "ws-yjs", ydoc);

// 编辑器定义规则，总体上分为三部分：
// 块级（blockSchema）、行级内容(inlineContentSchema)、修饰(styleSchema)
const schema = BlockNoteSchema.create({
  blockSpecs: {
    ...defaultBlockSpecs,
    blockAI: createReactBlockSpec(
      {
        type: "blockAI",
        content: "none",
        propSchema: {
          id: {
            default: "ai-block"
          },
          title: {
            default: "AI Block"
          },
          description: {
            default: "这是一个AI块的描述"
          },
          content: {
            default: "AI生成的内容"
          }
        }
      },
      {
        // 渲染器
        render: props => {
          const { id, title, description, content } = props.block.props;
          return (
            <div className="p-4 border rounded-lg shadow-md bg-gray-50 w-lg">
              <h3 className="text-lg font-semibold text-blue-600">{title}</h3>
              <p className="text-xs text-gray-500">{description}</p>
              <div className="mt-2 p-2 bg-white border rounded text-lg text-black">
                <strong>内容:</strong> {content}
              </div>

              <span className="text-xs text-gray-400">ID: {id}</span>
            </div>
          );
        }
      }
    ),
    // 自定义签名块
    blockSignature: createReactBlockSpec(
      {
        type: "blockSignature",
        content: "none",
        propSchema: {
          id: {
            default: "signature-block"
          },
          name: {
            default: "签名"
          }
        }
      },
      {
        // 渲染器
        render: props => {
          const { name } = props.block.props;
          return (
            // 美化一下下面的签名的样式
            <div className="flex items-center justify-between p-2 border rounded bg-gray-100">
              <span className="text-sm text-gray-600">签名：{name}</span>
            </div>
          );
        }
      }
    )
  },
  inlineContentSpecs: {
    ...defaultInlineContentSpecs,
    mention: createReactInlineContentSpec(
      {
        type: "mention",
        content: "none",
        propSchema: {
          id: {
            default: ""
          },
          name: {
            default: ""
          }
        }
      },
      {
        // 渲染器
        render: props => {
          console.log(props);
          const { id } = props.inlineContent.props;
          return <span className="text-blue-500 bg-amber-200">@{id}</span>;
        }
      }
    )
  },
  styleSpecs: {
    ...defaultStyleSpecs
  }
});

// 生成随机颜色（用于用户标识）
function getRandomColor() {
  return `#${Math.floor(Math.random() * 0xffffff)
    .toString(16)
    .padStart(6, "0")}`;
}

// 生成随机用户名
function getRandomName() {
  return `user-${Math.random().toString(36).slice(2, 8)}`;
}

export function DocEditorDemo() {
  const editor = useCreateBlockNote({
    schema,
    dictionary: zh,
    collaboration: {
      provider,
      fragment: ydoc.getXmlFragment("blocknote"),
      user: {
        name: getRandomName(), // 当前用户ID
        color: getRandomColor() // 当前用户颜色
      },
      renderCursor: cursorRender // 使用自定义光标渲染函数
    }
    // 使用 initialContent 初始化所有内容，包括自定义块和 mention
    // initialContent: [
    //   {
    //     type: "blockAI",
    //     props: {
    //       id: "ai-block-1",
    //       title: "AI生成内容",
    //       description: "这是一个AI块的描述",
    //       content: "AI生成的内容"
    //     }
    //   },
    //   {
    //     type: "blockSignature",
    //     props: {
    //       id: "signature-block-1",
    //       name: "张三"
    //     }
    //   },
    //   {
    //     type: "paragraph",
    //     content: [
    //       {
    //         type: "text",
    //         text: "这是一个测试段落，包含一个提及：",
    //         styles: {}
    //       },
    //       {
    //         type: "mention",
    //         props: { id: "User123", name: "用户123" }
    //       }
    //     ]
    //   }
    // ]
  });

  const getMentionUserItems = (e: typeof editor) => {
    const userItems: DefaultReactSuggestionItem[] = [
      {
        icon: <span>👤</span>,
        title: "用户123",
        onItemClick: () => {
          e.insertInlineContent([
            {
              type: "mention",
              props: { id: "User123", name: "用户123" }
            }
          ]);
        }
      },
      {
        icon: <span>👤</span>,
        title: "渡一用户123",
        onItemClick: () => {
          editor.insertInlineContent([
            {
              type: "mention",
              props: { id: "duyi123", name: "渡一用户123" }
            }
          ]);
        }
      }
    ];
    return userItems;
  };

  const insertBlockAI = (e: typeof editor) => {
    return {
      title: "AI助手",
      subtext: "自定义AI块",
      icon: <span>❤️</span>,
      onItemClick: () => {
        insertOrUpdateBlock(e, {
          type: "blockAI",
          props: {
            id: `ai-block-${Date.now()}`, // 使用时间戳生成唯一ID
            title: `AI生成标题`,
            description: `AI生成的描述`,
            content: `AI生成的内容`
          }
        });
      }
    };
  };

  // 插入签名块
  const insertBlockSignature = (e: typeof editor) => {
    return {
      title: "签名",
      subtext: "自定义签名块",
      icon: <span>✍️</span>,
      onItemClick: () => {
        insertOrUpdateBlock(e, {
          type: "blockSignature",
          props: {
            id: `signature-block-${Date.now()}`, // 这里应该是使用当前登录用户id
            name: `签名用户` // 这里应该是使用当前登录用户名称
          }
        });
      }
    };
  };

  return (
    <BlockNoteView editor={editor} slashMenu={false}>
      {/* 提示触发器 */}
      <SuggestionMenuController
        triggerCharacter="@"
        getItems={async query => {
          return filterSuggestionItems(getMentionUserItems(editor), query);
        }}
      />

      <SuggestionMenuController
        triggerCharacter="/"
        getItems={async query => {
          return filterSuggestionItems(
            [insertBlockSignature(editor), insertBlockAI(editor), ...getDefaultReactSlashMenuItems(editor)],
            query
          );
        }}
      />
    </BlockNoteView>
  );
}
